<template>
  <view class="pay">
    <!-- 1.0 收货地址 两种状态 -->
    <view
      v-if="address.userName"
      class="address"
      @tap="getAddressHandle"
    >
      <view class="address_detail">{{ addressDetail }}</view>
      <view class="address_info">
        <text class="address_text">{{ address.userName }}</text>
        <text class="address_text">{{ address.telNumber }}</text>
      </view>
    </view>
    <view
      v-else
      class="address_empty"
    >
      <view
        @tap="getAddressHandle"
        class="address_empty_button"
      >选择地址</view>
    </view>
    <!-- 2.0 商品列表 -->
    <view class="goods">
      <view class="goods_title">已选商品</view>
      <view class="goods_list">
        <view
          class="goods_item"
          v-for="item in cartList"
          :key="item.goods_id"
        >
          <goodsItem
            :item="item"
            v-if="item.goods_select"
          />
          <text class="goods_count">x{{ item.goods_count }}</text>
        </view>
      </view>
    </view>
    <!-- 3.0 底部固定栏 -->
    <view class="bottom">
      <text class="total_text">合计：</text>
      <text class="price">{{totalPrice}}</text>
      <view
        class="bottom_btn"
        :class="{ disabled: !address.userName }"
        @tap="payHandle"
      >去支付({{ totalCount }})</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      address: {},
      cartList: [],
    };
  },
  computed: {
    // 把零散数据拼接成完整地址
    addressDetail() {
      const { detailInfo, countyName, cityName, provinceName } = this.address;
      return provinceName + cityName + countyName + detailInfo;
    },
    // 计算 商品总价格
    totalPrice() {
      // 初始化总价
      let totalPrice = 0;
      // 遍历所有的选中商品
      this.cartList.forEach((item) => {
        if (item.goods_select) {
          // 总价计算：单价 * 数量 的累加
          totalPrice += item.goods_price * item.goods_count;
        }
      });
      // 返回总价
      return totalPrice;
    },
    totalCount() {
      // 情况1：淘宝App规则：选中勾勾有多少个
      // return this.cartList.filter((item) => item.goods_select).length;
      // 情况2：京东App规则：选中商品的 数量累加
      let totalCount = 0;
      this.cartList.forEach((item) => {
        if (item.goods_select) {
          totalCount += item.goods_count;
        }
      });
      return totalCount;
    },
  },
  onLoad() {
    // 页面加载的时候获取到收货地址
    this.address = uni.getStorageSync("address") || {};
    this.cartList = uni.getStorageSync("cartList") || [];
  },
  methods: {
    getAddressHandle() {
      // 调用微信<原生>的收货地址界面
      uni.chooseAddress({
        success: (res) => {
          // console.log(res);
          // 把收货地址保存到本地
          uni.setStorageSync("address", res);
          this.address = res;
        },
      });
    },
    async payHandle() {
      if (!this.address.userName) {
        return uni.showToast({ title: "请选择收货地址", icon: "none" });
      }
      // console.log("走支付逻辑");
      try {
        // 0.  确保已经是登录的(有token)
        // 1.  创建订单
        const goods = this.cartList
          .filter((item) => item.goods_select)
          // 解构赋值还可以这么写
          .map(({ goods_id, goods_price, goods_count: goods_number }) => ({
            goods_id,
            goods_price,
            goods_number,
          }));
        // 创建订单获取订单号
        const {
          message: { order_number },
        } = await this.$u.api.createOrder({
          order_price: this.totalPrice,
          consignee_addr: this.addressDetail,
          goods,
        });
        // console.log(1111, order_number);
        // 2.  根据订单生成支付对象
        const {
          message: { pay },
        } = await this.$u.api.orderPayParams({ order_number });
        // console.log(2222, pay);
        // 3.  调用支付接口 (微信原生的支付界面)
        await wx.requestPayment(pay);
        // 4.  验证支付状态
        const { message } = await this.$u.api.orderCheck({ order_number });
        // console.log(44444, message);

        // 支付成功后的流程
        uni.showToast({ title: "支付成功" });
        // 购物车删除掉已经支付的商品（保留未选择的商品）
        const cartList = this.cartList.filter((item) => !item.goods_select);
        uni.setStorageSync("cartList", cartList);
        // console.log(res);
        setTimeout(() => {
          // 页面替换到订单列表页
          uni.redirectTo({ url: "/pages/order/order" });
        }, 2000);
      } catch (error) {
        // console.log("错误对象", error);
        uni.showToast({ title: "支付失败", icon: "none" });
      }
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f9f9f9;
}
// 有收货地址的状态
.address {
  background-color: #fff;
  border-radius: 5rpx;
  margin: 20rpx;
  height: 188rpx;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .address_detail {
    font-size: 30rpx;
  }
  .address_info {
    font-size: 26rpx;
    .address_text {
      margin-right: 40rpx;
    }
  }
}
.address_empty {
  background-color: #fff;
  border-radius: 5rpx;
  margin: 20rpx;
  height: 188rpx;
  padding: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .address_empty_button {
    width: 300rpx;
    height: 90rpx;
    border-radius: 45rpx;
    color: #eb4450;
    border: 2rpx solid #eb4450;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 30rpx;
  }
}
.goods {
  background-color: #fff;
  border-radius: 5rpx;
  margin: 20rpx;
  padding: 20rpx;
  .goods_title {
    line-height: 60rpx;
    font-size: 30rpx;
    font-weight: bold;
  }

  .goods_list {
    .goods_item {
      position: relative;
      .goods_count {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
      }
    }
  }
}
// 2.0 底部固定栏
.bottom {
  height: 83rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top: 1rpx solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 20rpx;

  .price {
    font-size: 28rpx;
    flex: 1;
  }

  .bottom_btn {
    font-size: 22rpx;
    width: 150rpx;
    height: 52rpx;
    border-radius: 26rpx;
    color: #fff;
    background-color: #ea4350;
    display: flex;
    justify-content: center;
    align-items: center;
    &.disabled {
      background-color: #ccc;
    }
  }
}
</style>